﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using Project5.Models;

namespace Project5.Controllers
{
    public class AccountController : Controller
    {
        //
        // Get: /Account/Recovery
        [AllowAnonymous]
        public ActionResult RecoverySuccess()
        {
            return View();
        }

        //
        // Get: /Account/Recovery
        [AllowAnonymous]
        public ActionResult Recovery()
        {
            return RedirectToAction("RecoveryRequest");
        }

        //
        // POST: /Account/Recovery
        [AllowAnonymous]
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Recovery(RecoveryModel model)
        {
            // these are hidden fields and so this shouldn't happen, but....
            if (model.Email == null || model.Question == null)
            {
                return RedirectToAction("RecoveryRequest");
            }
            
            if (ModelState.IsValid)
            {
                string userName = Membership.GetUserNameByEmail(model.Email);

                if (string.IsNullOrEmpty(userName))
                {
                    ModelState.AddModelError("", "Database access error or the account for " + model.Email + " does not exist.");
                }
                else
                {
                    MembershipUser user = Membership.GetUser(userName);
                    if (user == null)
                    {
                        ModelState.AddModelError("", "Database access error, please try again.");
                    }
                    else 
                    {
                        try{
                            string newPassword = user.ResetPassword(model.Answer);
                            
                            // TODO: Call a method to email the password to the user
 
                            // TODO: remove the displayed password here and in the view
                            TempData["Password"] = newPassword;
                            return RedirectToAction("RecoverySuccess", "Account");
                        } 
                        catch(MembershipPasswordException mpe)
                        {
                             ModelState.AddModelError("", "Security answer is incorrect, please try again.");
                        }
                    }
                }
            }

            // If we got this far, something failed, redisplay form
            model.Answer = "";
            return View(model);
        }

        //
        // GET: /Account/RecoveryRequest
        [AllowAnonymous]
        public ActionResult RecoveryRequest()
        {
            return View();
        }

        //
        // POST: /Account/RecoveryRequest
        [AllowAnonymous]
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult RecoveryRequest(RecoveryRequestModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                //SqlMembershipProvider.ResetPassword(model.Email);
                string userName = Membership.GetUserNameByEmail(model.Email);
                
                if ( string.IsNullOrEmpty(userName) )
                {
                    ModelState.AddModelError("", "The account for " + model.Email + " does not exist.");
                }
                else
                {
                    MembershipUser user = Membership.GetUser(userName);
                    if (user == null)
                    {
                        ModelState.AddModelError("", "Database access error, please try again.");
                    }
                    else
                    {
                        RecoveryModel recoveryModel = new RecoveryModel();
                        recoveryModel.Email = model.Email;
                        recoveryModel.Question = user.PasswordQuestion;
                        return View("Recovery", recoveryModel);
                    }
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        //
        // GET: /Account/LogOn
        [AllowAnonymous]
        public ActionResult LogOn()
        {
            // check if user is already logged in ( i.e. "Remember Me" )
            if (Membership.GetUser() != null)
            {
               return RedirectToAction("Index", "Home");
            }
            return View();
        }

        //
        // POST: /Account/LogOn
        [AllowAnonymous]
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult LogOn(LogOnModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                if (Membership.ValidateUser(model.Email, model.Password))
                {
                    FormsAuthentication.SetAuthCookie(model.Email, model.RememberMe);
                    if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
                        && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
                    {
                        return Redirect(returnUrl);
                    }
                    else
                    {
                        return RedirectToAction("Index", "Home");
                    }
                }
                else
                {
                    ModelState.AddModelError("", "The user name or password provided is incorrect.");
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }
        
       

        //
        // GET: /Account/LogOff

        public ActionResult LogOff()
        {
            FormsAuthentication.SignOut();

            return RedirectToAction("Index", "Home");
        }

        //
        // GET: /Account/Register
        [AllowAnonymous]
        public ActionResult Register()
        {
            return View();
        }

        //
        // POST: /Account/Register
        [AllowAnonymous]
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Register(RegisterModel model)
        {
            if (ModelState.IsValid)
            {
                // Attempt to register the user
                MembershipCreateStatus createStatus;
                Membership.CreateUser(model.Email, model.Password, model.Email, model.Question, model.Answer, true, null, out createStatus);

                if (createStatus == MembershipCreateStatus.Success)
                {
                    FormsAuthentication.SetAuthCookie(model.Email, false /* createPersistentCookie */);
                    return RedirectToAction("Index", "Home");
                }
                else
                {
                    ModelState.AddModelError("", ErrorCodeToString(createStatus));
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        //
        // Get: /Account/EditAccount
        public ActionResult EditSuccess()
        {
           return View();
        }

        //
        // Get: /Account/EditAccount
        public ActionResult Edit()
        {
            // This throws an Argument Exception if the user is not already logged in.
            // No exception check since our default security ensures they are logged in.
            MembershipUser user = Membership.GetUser();

            EditModel model = new EditModel();
            model.Email = user.UserName;
            model.Question = user.PasswordQuestion;
            return View(model);
        }

        //
        // POST: /Account/Edit
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit(EditModel model)
        {
            if (ModelState.IsValid)
            {
                // Edit will throw an exception rather than return false in certain failure scenarios.
                bool updatesSucceeded;
                
                try
                {
                    MembershipUser currentUser = Membership.GetUser(User.Identity.Name, true /* userIsOnline */);
                    if (currentUser.UserName.Equals(model.Email))
                    {
                        updatesSucceeded = 
                            currentUser.ChangePasswordQuestionAndAnswer(model.Password, model.Question, model.Answer);
                    }
                    else
                    {
                        updatesSucceeded = false;
                    }
                }
                catch (Exception)
                {
                    updatesSucceeded = false;
                }

                if (updatesSucceeded)
                {
                    return RedirectToAction("EditSuccess");
                }
                else
                {
                    ModelState.AddModelError("", "Account update failed. If the problem continues, logout, login, and try again now or at a later time.");
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        //
        // GET: /Account/ChangePassword
        public ActionResult ChangePassword()
        {
            return View();
        }

        //
        // POST: /Account/ChangePassword
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult ChangePassword(ChangePasswordModel model)
        {
            if (ModelState.IsValid)
            {
                // ChangePassword will throw an exception rather
                // than return false in certain failure scenarios.
                bool changePasswordSucceeded;
                try
                {
                    MembershipUser currentUser = Membership.GetUser(User.Identity.Name, true /* userIsOnline */);
                    changePasswordSucceeded = currentUser.ChangePassword(model.OldPassword, model.NewPassword);
                }
                catch (Exception)
                {
                    changePasswordSucceeded = false;
                }

                if (changePasswordSucceeded)
                {
                    return RedirectToAction("ChangePasswordSuccess");
                }
                else
                {
                    ModelState.AddModelError("", "The current password is incorrect or the new password is invalid.");
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }
        
        //
        // GET: /Account/ChangePasswordSuccess
        public ActionResult ChangePasswordSuccess()
        {
            return View();
        }

       

        #region Status Codes
        private static string ErrorCodeToString(MembershipCreateStatus createStatus)
        {
            // See http://go.microsoft.com/fwlink/?LinkID=177550 for
            // a full list of status codes.
            switch (createStatus)
            {
                case MembershipCreateStatus.DuplicateUserName:
                    return "User name already exists. Please enter a different user name.";

                case MembershipCreateStatus.DuplicateEmail:
                    return "A user name for that e-mail address already exists. Please enter a different e-mail address.";

                case MembershipCreateStatus.InvalidPassword:
                    return "The password provided is invalid. Please enter a valid password value.";

                case MembershipCreateStatus.InvalidEmail:
                    return "The e-mail address provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidAnswer:
                    return "The password retrieval answer provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidQuestion:
                    return "The password retrieval question provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidUserName:
                    return "The user name provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.ProviderError:
                    return "The authentication provider returned an error. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                case MembershipCreateStatus.UserRejected:
                    return "The user creation request has been canceled. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                default:
                    return "An unknown error occurred. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
            }
        }
        #endregion
    }
}
